package com.atsmart.app.sql;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import com.atsmart.app.model.PositionAttributeInfo;

public class PositionSqlHelper {

	private SQLiteDatabase db = null;

	/**
	 * 打开数据库
	 */
	public void open(SqlHelper dh) {
		// dh = new SqlHelper(null, "atsmart", null,SqlHelper.getDBVersion());
		db = dh.getWritableDatabase();
	}

	public synchronized void addAttribute(PositionAttributeInfo at) {
		if (at == null) {
			return;
		}
		String strSql = "insert or replace into position_attribute (dur, sheet,open) values(?,?,?);";
		try {
			SQLiteStatement stm = db.compileStatement(strSql);
			stm.bindLong(1, at.dur);
			stm.bindString(2, at.sheet == null ? "" : at.sheet);
			stm.bindLong(3, at.open == null ? 0 : at.open);
			stm.execute();
			stm.clearBindings();
			stm.close();
		} catch (Exception e) {
			e.printStackTrace();
			// will not happen
		}
	}

	public PositionAttributeInfo getAttribute() {
		String sql = " select _id, dur, sheet,open from position_attribute";
		Cursor cursor = db.rawQuery(sql, null);
		PositionAttributeInfo historie = null;
		try {
			if (cursor != null && cursor.moveToFirst()) {
				historie = new PositionAttributeInfo();
				historie.id = cursor.getInt(0);
				historie.dur = cursor.getInt(1);
				historie.sheet = cursor.getString(2);
				historie.open = cursor.getInt(3);
			}
		} catch (Exception e) {
			return null;
		} finally {
			cursor.close();
		}
		return historie;
	}

	public void deleteAttribute() {
		// db.delete("position_attribute", null, null);
		db.execSQL("delete from position_attribute");
	}

	public void updateAttribute(Integer open) {
		ContentValues cv = new ContentValues();
		cv.put("open", open);
		db.update("position_attribute", cv, null, null);
	}

	public void updateSheetAndRate(String sheet,int rate) {
		ContentValues cv = new ContentValues();
		cv.put("sheet", sheet);
		cv.put("dur", rate);
		db.update("position_attribute", cv, null, null);
	}
}
